#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "lwip/api_shell.h"
#include "lwip/ip4_addr.h"
#include "lwip/netif.h"
#include "lwip/netifapi.h"

#include "cmsis_os2.h"
#include "ohos_init.h"
#include "wifi_device.h"
#include "wifi_error_code.h"
int g_wifiState = 0;

/**
 * @brief 打印WifiLinkedInfo信息
 * @param info 需要打印信息的WifiLinkedInfo指针
 */
static void PrintWifiLinkedInfo(WifiLinkedInfo *info)
{
    if (!info)
        return;

    static char macAddress[32] = {0};
    unsigned char *mac = info->bssid;
    snprintf(macAddress, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X",
             mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    printf("info: bssid: %s, rssi: %d, connState: %d, reason: %d, ssid: %s\r\n",
           macAddress, info->rssi, info->connState, info->disconnectedReason, info->ssid);
}

static void OnWifiConnectionChanged(int state, WifiLinkedInfo *info)
{
    if (!info)
        return;

    printf("%s %d, state = %d \r\n", __FUNCTION__, __LINE__, state);
    PrintWifiLinkedInfo(info);
    if(state > 0)
      g_wifiState = 1;
}

/**
 * @brief 毫秒级延时
 * @param ms 需要延迟的毫秒数
 */
static void Delay(uint32_t ms)
{
    uint32_t usPerTicks = (1000 * 1000) / osKernelGetTickFreq();
    osDelay((ms * 1000) / usPerTicks);
    usleep((ms * 1000) % usPerTicks);
}

static void WifiSTATask(void){
    WifiEvent wifiEventHandler = {.OnWifiConnectionChanged = OnWifiConnectionChanged };
    WifiDeviceConfig apConfig = {
        .ssid = "thinkgo",
        .preSharedKey = "12345678",
        .securityType = WIFI_SEC_TYPE_PSK};
    WifiErrorCode errCode = RegisterWifiEvent(&wifiEventHandler);
    printf("RegisterWifiEvent errCode: %d\r\n", errCode);
    int networkId = -1;
    //启动WiFi STA模式
    errCode = EnableWifi();
    if(errCode != WIFI_SUCCESS){
        printf("EnableWifi errCode: %d\r\n", errCode);
    }
    // 判断WIFI是否激活
    if (IsWifiActive() == 0) {
        printf("Wifi station is not active.\r\n");
    }
    errCode = AddDeviceConfig(&apConfig, &networkId);
    if(errCode != WIFI_SUCCESS){
        printf("AddDeviceConfig errCode: %d\r\n", errCode);
    }
    g_wifiState = 0;
    errCode = ConnectTo(networkId);
    printf("ConnectTo(%d) errCode: %d\r\n", networkId, errCode);
    while (!g_wifiState)
    {
        Delay(10);
    }
   printf("ConnectTo(%d) success: g_wifiState %d\r\n", networkId, g_wifiState);
    Delay(3000);

        // 联网业务开始
        // 这里是网络业务代码...
        struct netif *iface = netifapi_netif_find("wlan0");
        if (iface)
        {
            // 等待DHCP
            dhcp_start(iface);
    for (;;) {
        if (dhcp_is_bound(iface) == ERR_OK) {
            printf("<-- DHCP state:OK -->\r\n");
            // 打印获取到的IP信息
            netifapi_netif_common(iface, dhcp_clients_info_show, NULL);
            break;
        }
        osDelay(100);
    }} else
        {
            // 联网业务结束，断开和AP的连接
            Disconnect();
            RemoveDevice(networkId);

            //关闭WiFi STA模式
            errCode = DisableWifi();
            printf("DisableWifi errCode: %d\r\n", errCode);
            Delay(500);
        }

        errCode = UnRegisterWifiEvent(&wifiEventHandler);
        printf("UnRegisterWifiEvent errCode: %d\r\n", errCode);
}

static void WifiSTA(void)
{
    osThreadAttr_t attr;

    attr.name = "WifiSTATask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = 24;

    if (osThreadNew((osThreadFunc_t)WifiSTATask, NULL, &attr) == NULL) {
        printf("Failed to create WifiStaTask!\n");
    }
}

APP_FEATURE_INIT(WifiSTA);